package com.bjsxt.shopping.util.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.fileupload.*;

import java.sql.SQLException;
import java.util.*;
import java.util.regex.*;
import java.io.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import com.bjsxt.shopping.user.User;

public class Register extends HttpServlet { 
	//BLOB

	@Override
	public void init(ServletConfig config) throws ServletException {
		this.config = config;
	}

	private ServletConfig config = null;
	
	

	private File tempPath = new File("D:\\upload\\temp\\"); // ���ڴ����ʱ�ļ���Ŀ¼

	public void destroy() {
		config = null;
		super.destroy();
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse res)
			throws ServletException, IOException {
		// 取得web目录的绝对路径
        String webappPath = request.getSession().getServletContext().getRealPath("/");
        final String s = webappPath.substring(webappPath.length()-1, webappPath.length());
        if(s.equals(File.separator)){
            webappPath = webappPath + "upload" +  File.separator ;
        } else {
            webappPath = webappPath + File.separator + "upload" + File.separator ;
        }
        System.out.println("路径：--   "+webappPath);
		//String uploadPath = config.getInitParameter("uploadPath"); // 
		res.setContentType("text/html; charset=UTF-8");
		PrintWriter out = res.getWriter();
		System.out.println(request.getContentLength());
		System.out.println(request.getContentType());
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// maximum size that will be stored in memory
		factory.setSizeThreshold(4096);
		// the location for saving data that is larger than getSizeThreshold()
		factory.setRepository(tempPath);

		ServletFileUpload upload = new ServletFileUpload(factory);
		// maximum size before a FileUploadException will be thrown
		upload.setSizeMax(5000000);
		upload.setHeaderEncoding("UTF-8");
		String fileFullName = "";
		User u = new User();
		u.setRdate(new Date());
		u.setAcctype("1");
		
		try {
			List fileItems = upload.parseRequest(request);
			// assume we know there are two files. The first file is a small
			// text file, the second is unknown and is written to a file on
			// the server
			Iterator iter = fileItems.iterator();

		
			
			while (iter.hasNext()) {
				
				FileItem item = (FileItem) iter.next();
				
                if (item.getFieldName().equals("username")) {
                    u.setUsername(item.getString().trim());
                }
                if (item.getFieldName().equals("password")) {
                    u.setPassword(item.getString().trim());
                }
                if (item.getFieldName().equals("phone")) {
                    u.setPhone(item.getString().trim());
                }
                if (item.getFieldName().equals("addr")) {
                    u.setAddr(item.getString().trim());
                }
                if (!item.isFormField() && item.getFieldName().equals("file")) {
                	fileFullName = item.getName();
                	System.out.println();
                	final String url = webappPath+u.getUsername()+fileFullName;
                	final File ff = new File(url );
                    item.write(ff);
                    u.setAttach(u.getUsername()+item.getName().trim());
                }
//				
				if (!item.isFormField()) {
					String name = item.getName();
					long size = item.getSize();
					if ((name == null || name.equals("")) && size == 0)
						continue;
					
					
				}
			}
		} catch (FileUploadException e) {
			out.println(e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		

		boolean resSucc;
		try {
			resSucc = u.save();
			if (resSucc) {
				u.setLoginname(u.getUsername());
				request.getSession().setAttribute("user", u);
				res.sendRedirect(request.getContextPath()+"/RegistSuccessful.jsp");
			} else {
				out.println("出现错误，未成功注册，请联系管理员!");
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
		

	}
	/**
     * 取得文件格式。
     * <p>
     * 该方法取得文件名最后一个"."所在的位置，然后返回该位置后的字符串。
     * </p>
     * 
     * @param fileName 文件名
     * @return String 文件格式
     */
    private String getFileFormat(String fileName) {
        final int dotIndex = fileName.lastIndexOf('.');
        if(dotIndex==-1){
            return null;
        }else{
            return fileName.substring(dotIndex + 1);
        }
        //return dotIndex == -1 ? null : fileName.substring(dotIndex + 1);
    }

}
